<?php

namespace Core\Log\Driver;

class File {

    protected $config  =   array(
        'time_format'   =>  ' c ',
        'file_size'     =>  2097152,
        'path'          =>  '',
    );

    // 实例化并传入参数
    public function __construct($config=array()){
        $this->config   =   array_merge($this->config,$config);
    }

    /**
     * 日志写入接口
     * 
     * @access public
     * @param string $log 日志信息
     * @param string $destination 写入目标
     * @return void
     */
    public function write($log, $destination = '')
    {
        $log_str = '';
        foreach ($log as $val) {
            $log_str .= "{$val[0]}: {$val[1]}\r\n";
        }
        $now = date($this->config['time_format']);
        if (empty($destination))
            $destination = $this->config['path'] . date('y_m_d') . '.log';
            // 自动创建日志目录
        $log_dir = dirname($destination);
        if (! is_dir($log_dir)) {
            mkdir($log_dir, 0755, true);
        }
        // 检测日志文件大小，超过配置大小则备份日志文件重新生成
        if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination))
            rename($destination, dirname($destination) . '/' . time() . '-' . basename($destination));
        $param = '';
        if (! empty(file_get_contents('php://input'))) {
            $param .= "raw = " . file_get_contents('php://input') . "\r\n";
        }
        if (! empty($_POST)) {
            $param .= "post = " . json_encode($_POST) . "\r\n";
        }
        if (! empty($_GET)) {
            $param .= "get = " . json_encode($_GET) . "\r\n";
        }
        if (! empty($_COOKIE)) {
            $param .= "cookie = " . json_encode($_COOKIE) . "\r\n";
        }
        // if (getConfig('debug_log_user')){
        //     $users = explode(',', getConfig('debug_user'));
        //     $userID = getUserSession(isset($_COOKIE["tokenvals"]) ? $_COOKIE["tokenvals"] : "");
        //     if (in_array($userID, $users)){
        //         error_log("[{$now}] " . $_SERVER['REMOTE_ADDR'] . ' ' . $_SERVER['REQUEST_URI'] . "\r\n{$param}{$log_str}\r\n", 3, $destination);
        //     }
        // } else {
        //     error_log("[{$now}] " . $_SERVER['REMOTE_ADDR'] . ' ' . $_SERVER['REQUEST_URI'] . "\r\n{$param}{$log_str}\r\n", 3, $destination);
        // }

        error_log("[{$now}] " . $_SERVER['REMOTE_ADDR'] . ' ' . $_SERVER['REQUEST_URI'] . "\r\n{$param}{$log_str}\r\n", 3, $destination);
    }
}

